package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username" json:"user"`
	Password string `form:"password" json:"pwd"`
}

func main() {
	r := gin.Default()
	r.LoadHTMLFiles("./index.html")
	r.GET("/user", func(c *gin.Context) {
		//http://127.0.0.1:9090/user?username=wer&password=yui
		//1.方法一
		//username:=c.Query("username")
		//password:=c.Query("password")
		//u:=UserInfo{
		//	username:username,
		//	password:password,
		//}
		//fmt.Printf("%#v \n",u)
		//c.JSON(http.StatusOK, gin.H{
		//	"message": "ok",
		//})
		//2.方法二
		var u UserInfo          //声明一个UserInfo类型的变量u
		err := c.ShouldBind(&u) //
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v \n", u)
			c.JSON(http.StatusOK, gin.H{
				"status": "OK",
			})
		}

	})

	//http://127.0.0.1:9090/index
	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	//可以进入到postman中进行测试
	r.POST("/form", func(c *gin.Context) {
		var u UserInfo          //声明一个UserInfo类型的变量u
		err := c.ShouldBind(&u) //
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v \n", u)
			c.JSON(http.StatusOK, gin.H{
				"status": "OK",
			})
		}
	})
	r.POST("/json", func(c *gin.Context) {
		var u UserInfo          //声明一个UserInfo类型的变量u
		err := c.ShouldBind(&u) //
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v \n", u)
			c.JSON(http.StatusOK, gin.H{
				"status": "OK",
			})
		}
	})

	r.Run(":9090")
}
